package states
{
	import Box2D.Collision.b2Bound;
	import Box2D.Collision.Shapes.b2Shape;
	import Box2D.Dynamics.b2Body;
	import Box2D.Dynamics.b2FixtureDef;
	import flash.display.Stage;
	import gameObjects.Car;
	import gameObjects.GameObject;
	import gameObjects.Wall;
	import physics.PhysicsManager;
	/**
	 * ...
	 * @author ...
	 */
	public class Gameplay implements IState
	{
		//private const/var
		private var m_stage:Stage = null;
		private var m_phyMgr:PhysicsManager = null;
		private var m_vGameObjecs:Vector.<GameObject> = null;
		private var m_p1:Car = null;
		
		/* public functions */
		public function Gameplay()
		{
			
		}
		
		public function initialize(theStage:Stage):void
		{
			if (theStage) m_stage = theStage;
			m_stage.focus = m_stage;
			if (!m_vGameObjecs) m_vGameObjecs = new Vector.<GameObject>();
			
			initAllObjects();
			addEventListeners();
		}
		
		public function update():void
		{
			if (m_phyMgr) m_phyMgr.update();
			if (m_p1) m_p1.update();
		}
		
		public function uninitialize():void
		{
			
		}
		
		public function destroy():void
		{
			if (m_stage)
			{
				removeAllEventListeners();
				removeAllObjects();
			}
		}
		
		/* private functions */
		private function initAllObjects():void
		{
			if (!m_phyMgr) m_phyMgr = new PhysicsManager(m_stage, false, true);
			if (!m_p1) m_p1 = new Car(m_stage, m_phyMgr, 570, 500, Globals.uiTAG_P1_CAR);
			
			var topWall:Wall = new Wall(m_phyMgr, m_stage.stageWidth / 2, 1, m_stage.stageWidth / 2, 2, 0);
			m_vGameObjecs.push(topWall);
			
			var bottomWall:Wall = new Wall(m_phyMgr, m_stage.stageWidth / 2, m_stage.stageHeight - 1, m_stage.stageWidth / 2, 2, 0);
			m_vGameObjecs.push(bottomWall);
			
			var leftWall:Wall = new Wall(m_phyMgr, 1, m_stage.stageHeight / 2, 2, m_stage.stageHeight / 2, 0);
			m_vGameObjecs.push(leftWall);
			
			var rightWall:Wall = new Wall(m_phyMgr, m_stage.stageWidth - 1, m_stage.stageHeight / 2, 2, m_stage.stageHeight / 2, 0);
			m_vGameObjecs.push(rightWall);
		}
		
		private function addEventListeners():void
		{
			
		}
		
		private function removeAllEventListeners():void
		{
			
		}
		
		private function removeAllObjects():void
		{
			if (m_p1)
			{
				m_p1.destroy(m_stage);
				m_p1 = null;
			}
			
			if (m_phyMgr)
			{
				m_phyMgr.destroy();
				m_phyMgr = null;
			}
			
			if (m_stage) m_stage = null;
			
			if (m_vGameObjecs)
			{
				var iGoLen:int = m_vGameObjecs.length;
				for each(var go:GameObject in m_vGameObjecs)
				{
					if (go)
					{
						if (go.sprite && m_stage.contains(go.sprite))
						{
							m_stage.removeChild(go.sprite);
							go.sprite = null;
						}
						
						if (go.body && m_phyMgr)
						{
							m_phyMgr.destroyBody(go.body);
						}
					}
				}
				m_vGameObjecs.splice(0, iGoLen);
			}
		}
	}

}
